/**
 * Live GPS Tracking Application
 * Track information screen
 *
 * Copyright 2009, Ivar Clemens
 */

package nl.ivarclemens.gpstrack.ui;

import nl.ivarclemens.gpstrack.nmea.PositionEvent;
import nl.ivarclemens.gpstrack.track.MemTrack;
import nl.ivarclemens.gpstrack.GPSTrack;
import javax.microedition.lcdui.*;

public class TrackUI extends Form implements CommandListener, PositionEvent {

    private GPSTrack gpstrack = null;
    private Command backCommand;
    private Command clearCommand;
    private MemTrack liveTrack = null;

    private StringItem numPoints = null;
    private StringItem distance = null;

    public TrackUI(GPSTrack gpstrack, MemTrack track)
    {
        super("Current track");

        this.gpstrack = gpstrack;
        this.liveTrack = track;

        this.gpstrack.getNMEAParser().addPositionListener(this);

        numPoints = new StringItem("Points:", "0");
        distance = new StringItem("Distance:", "0");

        this.append(numPoints);
        this.append(distance);

        backCommand = new Command("Back", Command.BACK, 2);
        clearCommand = new Command("Clear", Command.ITEM, 1);

        this.addCommand(backCommand);
        this.addCommand(clearCommand);
        this.setCommandListener(this);
    }

    public void posUpdate(long time, double lat, double lon, double ang, double vel)
    {
        int n = liveTrack.numPoints();

        numPoints.setText("" + n);

        double dist = 0;
        for(int i = 1; i < n; i++)
            dist = dist + liveTrack.getDistance(i);

        String distStr = Double.toString(dist);
        distStr = distStr.substring(0, Math.min(7, distStr.length()));

        distance.setText(distStr + "km");
    }

    public void commandAction(Command c, Displayable d)
    {
        if(c == clearCommand)
            liveTrack.clear();

        if(c == backCommand)
            gpstrack.gotoScreen("menu");
    }
}
